 <?php

/**
 * Description of keyword
 * 
 * @author 叶风
 * Qq:    355007778
 * Email: ye.fn@163.com
 */
class keyword 
{
    function set($opt, $val)
    {
        $this->$$opt = $val;
        return $this;
    }

    /**
     * 注销词组中的单词
     * @var boolean
     */
    var $un_singleWord = false;
    
    
    /**
     * 计算单词出现的个数
     * 
     * @var boolean
     */
    var $word_count = false;
    
    /**
     * 分析关键词
     * @param string $str
     * @param int $splitNum
     * @return array
     */
	function splitKeyword($str, $splitNum=5)
	{
        if ($splitNum>0)
            $limit = $this->un_singleWord ? $splitNum+$splitNum : $splitNum;
        else
            $limit = '';
        $db = YF_f::get_db_link();
		$str = $db->escape(strip_tags($str));
		$res = $db->get('keyword','id,word', "'$str' like CONCAT('%',word,'%')", 'FF DESC,TF DESC', $limit);
		
		//注销短词
		if ($this->un_singleWord)
		 {
            foreach ($res as $k=>$v)
             {
                if (isset($res[$k]))
                foreach ($res as $k2=>$v2)
                 {
                   if ($k==$k2 or !isset($res[$k2]))
                       continue;
                   if (strlen($v2['word'])<4 && strpos($v['word'], $v2['word'])!==false)
                       unset($res[$k2]);
                 }
             }
            if ($splitNum)
                $res = array_slice($res, 0, $splitNum);
		 }
		
        //出现的频率
        if ($this->word_count)
         {   
            foreach ($res as $k=>$v)
                $res[$k]['num'] = substr_count($str, $v['word']); 
         }
        
		return $res;	
	}
    
    
    /**
     * 提取多个关键词，以空格分隔
     * @param string $str
     * @return string
     */
    function getKeys($str, $splitNum=3)
    {
        $kA = $this->splitKeyword($str);
        $a = array();
        foreach ($kA as $v)
            $a[] = $v['word'];
        return implode(' ', $a);
    }
}
